﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CaroLibraly;
using System.Collections;

namespace CaroServer
{
    public class Server : MarshalByRefObject, IServer
    {
        private ArrayList _listPlayer;
        private ArrayList _listRoom;

        public Server()
        {
            this._listPlayer = new ArrayList();
            this._listRoom = new ArrayList();
        }

        public bool Connected
        {
            get { return true; }
        }

        public ArrayList ListPlayer()
        {
            return this._listPlayer;
        }

        public ArrayList ListRoom()
        {
            return this._listRoom;
        }

        public void JoinServer(Player pl)
        {
            this._listPlayer.Add(pl);
            Program.frmMain.NewPlayerJoin(pl);
            Program.frmMain.ExitsPlayer = true;
        }

        public void LeaveServer(Player pl)
        {
            this._listPlayer.Remove(pl);
            Room tmp;
            for (int i = this._listRoom.Count - 1; i >= 0; i--)
            {
                tmp = this._listRoom[i] as Room;
                if (tmp.Owner.Ip == pl.Ip)
                {
                    this._listRoom.RemoveAt(i);
                    Program.frmMain.RemoveRom(tmp);
                }
            }
            Program.frmMain.PlayerLeave(pl);
            Program.frmMain.ExitsPlayer = (this._listPlayer.Count == 0);
        }

        public void CreateRoom(Room r)
        {
            this._listRoom.Add(r);
            Program.frmMain.NewRoomCreate(r);
        }

        public bool JoinRoom(Room r, Player pl)
        {
            foreach (Room room in this._listRoom)
                //if (!room.Full && room.Owner.Ip == r.Owner.Ip)
                if (!room.Full && room.Owner.Ip == r.Owner.Ip && room.Owner.Name == r.Owner.Name)
                {
                    room.SetRival(pl);
                    Program.frmMain.NewPlayerJoinRoom(r);
                    return true;
                }
            return false;
        }

        public void RemoveRoom(Room r)
        {
            Room tmp;
            for (int i = this._listRoom.Count - 1; i >= 0; i--)
            {
                tmp = this._listRoom[i] as Room;
                if (tmp.Owner.Ip == r.Owner.Ip)
                {
                    this._listRoom.RemoveAt(i);
                    Program.frmMain.RemoveRom(tmp);
                }
            }
        }
    }
}
